import router from "../router";
import axios from 'axios'
import {refreshToke,isRefreshRequest} from "../service/token.ts";
import {getToken, setToken} from "./common.ts";
import tokenEnums from "../access/tokenEnums.ts";
import type {AxiosRequestConfig } from "axios";
import {ResponseData} from "./ResponseData.ts";



// 创建实例
let http = axios.create({
    baseURL: 'http://localhost:8080/api',
    timeout: 50000,  // 毫秒
    headers:{
        token:getToken(tokenEnums.ACCESS_TOKEN)
    }
})

//响应拦截器
// @ts-ignore
http.interceptors.response.use(async res => {
    //从响应设置accessToken
    if (res.data.data?.accessToken) {
        setToken(tokenEnums.ACCESS_TOKEN,res.data.data.accessToken)
        http.defaults.headers.token = getToken(tokenEnums.ACCESS_TOKEN);
    }

    //从响应设置refreshToken
    if (res.data.data?.refreshToken) {
        setToken(tokenEnums.REFRESH_TOKEN,res.data.data.refreshToken)
    }
    //判断
    if (res.data.code !==0) {
        if (res.data.code === 40101) {
            //无权限
            await router.push('/noAuth');
        } else if (res.data.code === 40102 &&  !await isRefreshRequest(res.config)) {
            //刷新token
            console.log("accessToken过期，自动刷新token")
            const isSuccessful = await refreshToke();
            if (isSuccessful){
                //重新请求
                res.config.headers.token = getToken(tokenEnums.ACCESS_TOKEN);
                return await http.request(res.config);
            }
            else {
                console.log("刷新token失败，跳转到登录页面")
                //跳转到登录页面
            }
        } else if (res.data.code === 40100) {
            //未登录)
            await router.push('/about');
        }else {
            alert(res.data.message)
        }
        // return Promise.reject(res.data)
    } else {
        return res
    }
}, err => {
    console.log("响应错误，原因：",+err)
    return Promise.reject(err)
})

//类型封装,改造成泛型函数
const request = async <T = any>(config: AxiosRequestConfig): Promise<ResponseData<T>> => {
    const {data} = await http.request<ResponseData<T>>(config)
    return data
}



export default request;




